import json

from playwright.sync_api import Playwright, sync_playwright


def run(playwright: Playwright) -> None:
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context(base_url="http://81.70.166.221:8080")
    page = context.new_page()
    page.goto("/login")
    page.get_by_role("textbox", name="用户名").click()
    page.get_by_role("textbox", name="用户名").fill("admin")
    page.get_by_role("textbox", name="密码").click()
    page.get_by_role("textbox", name="密码").fill("admin123")
    page.get_by_role("button", name="登录").click()
    # 等待页面跳转，作为登录成功的标准
    page.wait_for_url(url='http://81.70.166.221:8080/index')
    # page.pause()

    # 保存storage state 到指定的文件
    # 使用该方法前，需要确认网站cookie的失效时间
    storage = context.storage_state(path='../../auth/ry_auto.json')
    print(storage)
    # ---------------------
    context.close()
    browser.close()


with sync_playwright() as playwright:
    run(playwright)
